package com.stud.seckill.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.stud.seckill.common.enums.CacheKeyEnum;
import com.stud.seckill.common.config.CacheService;
import com.stud.seckill.mapper.UserMapper;
import com.stud.seckill.entity.UserEntity;
import com.stud.seckill.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Libra
 * @since 2024-03-29
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserEntity> implements UserService {

    @Autowired
    private CacheService cacheService;

    @Override
    public void add(UserEntity user) {
        user.setRegisterDate(new Date());
        user.setLoginCount(0);

        this.getBaseMapper().insert(user);
    }

    @Override
    public UserEntity get(String mobile) {
        UserEntity user = (UserEntity) cacheService.get(CacheKeyEnum.用户, mobile);
        if (user == null) {
            LambdaQueryWrapper<UserEntity> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.eq(UserEntity::getMobile, mobile);
            user = this.getBaseMapper().selectOne(queryWrapper);
            cacheService.set(CacheKeyEnum.用户, mobile, user);
        }
        return user;
    }

    @Override
    public void loginSuccess(Long userId) {
        LambdaUpdateWrapper<UserEntity> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.setSql("login_count = login_count+1");
        updateWrapper.set(UserEntity::getLastLoginDate, new Date());
        updateWrapper.eq(UserEntity::getId, userId);
        this.update(updateWrapper);
    }

}
